<?php

/**
 * TimeTracker actions.
 *
 * @package    time-tracker
 * @subpackage TimeTracker
 * @author     Carlo Di Fulco
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class TimeTrackerActions extends sfActions
{
	/**
	 * Executes index action
	 *
	 * @param sfRequest $request A request object
	 */
	public function executeIndex(sfWebRequest $request)
	{
		//$this->forward('default', 'module');
		//    $this->appName = sfConfig::get('appname');
	}

	/**
	 *
	 * @extdirect-enable
	 * @extdirect-len 4
	 * @extdirect-formhandler
	 *
	 */
	public function executeCreateProject()
	{

		try {
			$project = new TtProject();

			$project->setName($this->getRequestParameter('name'));
			$project->setDescription($this->getRequestParameter('description'));

			$now = date(DateTime::W3C);

			$project->setCreatedAt($now);

			if($this->getRequestParameter('start')){
				$project->setStartedAt($now);
			}

			$project->save();

			$this->result = array('success' => true);
		} catch (Exception $e) {
			$this->result = array(
							'success'	=> false, 
							'msg'		=> $e->getMessage() 
			);
		}
			
		return sfView::SUCCESS;
	}

	/**
	 *
	 * @extdirect-enable
	 * @extdirect-len 3
	 * @extdirect-formhandler
	 *
	 */
	public function executeCreateTask()
	{

		try {
			$project = Doctrine_Core::getTable('TtProject')
						->findBy('id', $this->getRequestParameter('project'))
						->getFirst(); 
						
			$task = new TtTask();

			$task->setName($this->getRequestParameter('name'));
			$task->setDescription($this->getRequestParameter('description'));
			$now = date(DateTime::W3C);
			$task->setCreatedAt($now);
			$task->setIsShow((int)$this->getRequestParameter('show'));
			$task->setStatus('created');
			 
			$project->TtTask->add($task);
			
			$task->save(); 			

						
			if($this->getRequestParameter('start')){
				$task->start();
			}
			
			$this->result = array('success' => true, 'taskId' => $task->getId());

		} catch (Exception $e) {
			$this->result = array(
				'success'		=> false, 
				'msg'			=> $e->getMessage() 
			);
		}
			
		return sfView::SUCCESS;
	}

  
/**
	 *
	 *	Checks for started tasks when refreshing the page
	 *
	 * @extdirect-enable
	 * @extdirect-len 1
	 *
	 */
	public function executeCheckStartedTasks()
	{
		
		if($pending = TtTaskTable::findPendings()){
			
			$this->result = array(
				
				'success' 	=> false, 
				'taskName' 	=> $pending->getName(), 
				'taskId' 	=> $pending->getId()
			
			); 
			
		} else {
			
			$this->result = array('success' => true); 
			
		}
		 	
		return sfView::SUCCESS;
		
	}

}
